//
//  CalendarViewController.m
//  CangLongWnnianli
//
//  Created by 暗流澎涌 on 2025/7/2.
//

#import "CalendarViewController.h"
#import "CalendarDetailViewController.h"
#import <Masonry/Masonry.h>

@interface CalendarViewController () <UITableViewDataSource, UITableViewDelegate, UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate>

@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UIView *searchContainerView;
@property (nonatomic, strong) UIView *separatorLine;
@property (nonatomic, strong) UITextField *monthField;
@property (nonatomic, strong) UITextField *eventField;
@property (nonatomic, strong) UIButton *searchButton;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSArray *dataSource;
@property (nonatomic, strong) UIPickerView *monthPicker;
@property (nonatomic, strong) UIPickerView *eventPicker;
@property (nonatomic, strong) NSArray *monthOptions;
@property (nonatomic, strong) NSArray *eventOptions;
@property (nonatomic, strong) UIView *emptyView;
@property (nonatomic, strong) UILabel *emptyLabel;
@property (nonatomic, strong) UIButton *backButton;

@end

@implementation CalendarViewController

- (void)viewDidLoad {
    self.edgesForExtendedLayout = UIRectEdgeAll;
    self.extendedLayoutIncludesOpaqueBars = YES;
    [super viewDidLoad];
    [self setupUI];
    [self checkAvailableDataFiles];
    
    // 添加默认数据加载
    [self performSelector:@selector(loadDefaultData) withObject:nil afterDelay:0.1];
}

// 添加新方法
- (void)loadDefaultData {
    // 确保monthField和eventField已经有默认值
    if (self.monthField.text && self.eventField.text && 
        self.monthField.text.length > 0 && self.eventField.text.length > 0) {
        // 自动执行搜索
        [self searchDataFromDatalist];
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:NO];
}

- (void)setupUI {
    self.view.backgroundColor = [UIColor colorWithRed:0.98 green:0.98 blue:0.96 alpha:1.0];
    // 顶部headerView
    self.headerView = [[UIView alloc] init];
    self.headerView.backgroundColor = [UIColor colorWithRed:0.773 green:0.188 blue:0.188 alpha:1.0];
    [self.view addSubview:self.headerView];
    
    // 添加返回按钮
    self.backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.backButton setTitle:@"←" forState:UIControlStateNormal];
    [self.backButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.backButton.titleLabel.font = [UIFont systemFontOfSize:20];
    [self.backButton addTarget:self action:@selector(backButtonTapped) forControlEvents:UIControlEventTouchUpInside];
    [self.headerView addSubview:self.backButton];
    
    // 标题
    self.titleLabel = [[UILabel alloc] init];
    self.titleLabel.text = @"吉日查询";
    self.titleLabel.font = [UIFont boldSystemFontOfSize:20];
    self.titleLabel.textColor = [UIColor whiteColor];
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    [self.headerView addSubview:self.titleLabel];
    // 创建搜索容器视图
    self.searchContainerView = [[UIView alloc] init];
    self.searchContainerView.backgroundColor = [UIColor whiteColor];
    self.searchContainerView.layer.cornerRadius = 5;
    self.searchContainerView.layer.shadowColor = [UIColor blackColor].CGColor;
    self.searchContainerView.layer.shadowOffset = CGSizeMake(0, 2);
    self.searchContainerView.layer.shadowOpacity = 0.1;
    self.searchContainerView.layer.shadowRadius = 4;
    [self.view addSubview:self.searchContainerView];
    
    // 下拉选择和搜索
    self.monthField = [[UITextField alloc] init];
    self.monthField.placeholder = @"选择月份";
    self.monthField.font = [UIFont systemFontOfSize:16];
    self.monthField.textAlignment = NSTextAlignmentCenter;
    self.monthField.backgroundColor = [UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:1.0];
    self.monthField.textColor = [UIColor blackColor];
    self.monthField.borderStyle = UITextBorderStyleNone;
    self.monthField.layer.cornerRadius = 4;
    [self.searchContainerView addSubview:self.monthField];
    
    // 垂直分隔线
    self.separatorLine = [[UIView alloc] init];
    self.separatorLine.backgroundColor = [UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:1.0];
    [self.searchContainerView addSubview:self.separatorLine];
    
    self.eventField = [[UITextField alloc] init];
    self.eventField.placeholder = @"结婚";
    self.eventField.font = [UIFont systemFontOfSize:16];
    self.eventField.textAlignment = NSTextAlignmentCenter;
    self.eventField.backgroundColor = [UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:1.0];
    self.eventField.textColor = [UIColor blackColor];
    self.eventField.borderStyle = UITextBorderStyleNone;
    self.eventField.layer.cornerRadius = 4;
    [self.searchContainerView addSubview:self.eventField];
    
    self.searchButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.searchButton setImage:[UIImage systemImageNamed:@"magnifyingglass"] forState:UIControlStateNormal];
    self.searchButton.tintColor = [UIColor colorWithRed:0.773 green:0.188 blue:0.188 alpha:1.0];
    self.searchButton.backgroundColor = [UIColor clearColor];
    [self.searchButton addTarget:self action:@selector(searchAction) forControlEvents:UIControlEventTouchUpInside];
    [self.searchContainerView addSubview:self.searchButton];
    // 表格
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.view addSubview:self.tableView];
    
    // 创建空数据提示视图
    self.emptyView = [[UIView alloc] init];
    self.emptyView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.emptyView];
    
    self.emptyLabel = [[UILabel alloc] init];
    self.emptyLabel.text = @"暂无数据";
    self.emptyLabel.font = [UIFont systemFontOfSize:16];
    self.emptyLabel.textColor = [UIColor colorWithRed:0.6 green:0.6 blue:0.6 alpha:1.0];
    self.emptyLabel.textAlignment = NSTextAlignmentCenter;
    [self.emptyView addSubview:self.emptyLabel];
    
    [self.emptyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.emptyView);
    }];
    // 初始化为空数据
    self.dataSource = @[];
    
    // 生成从当前月份开始的12个月选项
    self.monthOptions = [self generateMonthOptions];
    self.eventOptions = @[@"结婚",
        @"上梁", @"乘船", @"习艺", @"买房", @"买衣服", @"买车", @"交易", @"伐木", @"会亲友", @"作梁",
        @"作灶", @"修坟", @"修造", @"入殓", @"出火", @"出行", @"出行上任", @"出货财", @"分居", @"割蜜",
        @"动土", @"动手术", @"合婚订婚", @"合寿木", @"合嵴", @"合帐", @"坏垣", @"塑绘", @"塞穴", @"大事勿用",
        @"安床", @"安机械", @"安葬", @"安装器具", @"安门", @"安香", @"定磉", @"建房", @"开业", @"开仓",
        @"开光", @"开厕", @"开工开业", @"开柱眼", @"开池", @"开渠", @"开生坟", @"归宁", @"归岫", @"成人礼",
        @"成服", @"房屋清洁", @"打扫", @"打猎", @"打鱼", @"拆卸", @"挂匾", @"掘井", @"探病", @"搬家",
        @"搬新房", @"收养子女", @"放水", @"教牛马", @"斋醮", @"断蚁", @"无", @"普渡", @"架马", @"栽种",
        @"求医", @"求子", @"求职入学", @"沐浴", @"治病", @"牧养", @"理发", @"盖屋", @"破土", @"破屋",
        @"祈福", @"祭祀", @"移柩", @"立碑", @"竖柱", @"筑堤", @"签订合同", @"纳婿", @"纳畜", @"纳财",
         @"结网", @"美甲浴足", @"行丧", @"补垣", @"装修", @"订盟", @"诉讼", @"诸事不宜", @"谢土",
        @"赴任", @"起基", @"迁坟", @"造仓", @"造庙", @"造桥", @"造畜稠", @"造船", @"造车器", @"针灸",
        @"铺路", @"问名", @"除服", @"除虫", @"雇庸", @"雕刻", @"馀事勿取"
    ];
    self.monthPicker = [[UIPickerView alloc] init];
    self.monthPicker.delegate = self;
    self.monthPicker.dataSource = self;
    self.eventPicker = [[UIPickerView alloc] init];
    self.eventPicker.delegate = self;
    self.eventPicker.dataSource = self;
    
    // 为monthField创建带按钮的输入视图
    UIView *monthInputView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UIScreen.mainScreen.bounds.size.width, 250)];
    monthInputView.backgroundColor = [UIColor colorWithRed:0.95 green:0.95 blue:0.95 alpha:1.0];
    
    // 添加工具栏
    UIToolbar *monthToolbar = [[UIToolbar alloc] init];
    monthToolbar.backgroundColor = [UIColor whiteColor];
    [monthInputView addSubview:monthToolbar];
    
    UIBarButtonItem *monthCancelButton = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(monthCancelTapped)];
    monthCancelButton.tintColor = [UIColor blackColor];
    UIBarButtonItem *monthFlexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    UIBarButtonItem *monthDoneButton = [[UIBarButtonItem alloc] initWithTitle:@"确定" style:UIBarButtonItemStyleDone target:self action:@selector(monthDoneTapped)];
    monthDoneButton.tintColor = [UIColor colorWithRed:0.773 green:0.188 blue:0.188 alpha:1.0];
    monthToolbar.items = @[monthCancelButton, monthFlexSpace, monthDoneButton];
    
    // 先添加picker到容器中，再设置约束
    [monthInputView addSubview:self.monthPicker];
    
    [monthToolbar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(monthInputView);
        make.height.mas_equalTo(44);
    }];
    
    [self.monthPicker mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(monthToolbar.mas_bottom);
        make.left.right.bottom.equalTo(monthInputView);
    }];
    
    // 为eventField创建带按钮的输入视图
    UIView *eventInputView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UIScreen.mainScreen.bounds.size.width, 250)];
    eventInputView.backgroundColor = [UIColor colorWithRed:0.95 green:0.95 blue:0.95 alpha:1.0];
    
    // 添加工具栏
    UIToolbar *eventToolbar = [[UIToolbar alloc] init];
    eventToolbar.backgroundColor = [UIColor whiteColor];
    [eventInputView addSubview:eventToolbar];
    
    UIBarButtonItem *eventCancelButton = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(eventCancelTapped)];
    eventCancelButton.tintColor = [UIColor blackColor];
    UIBarButtonItem *eventFlexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    UIBarButtonItem *eventDoneButton = [[UIBarButtonItem alloc] initWithTitle:@"确定" style:UIBarButtonItemStyleDone target:self action:@selector(eventDoneTapped)];
    eventDoneButton.tintColor = [UIColor colorWithRed:0.773 green:0.188 blue:0.188 alpha:1.0];
    eventToolbar.items = @[eventCancelButton, eventFlexSpace, eventDoneButton];
    
    // 先添加picker到容器中，再设置约束
    [eventInputView addSubview:self.eventPicker];
    
    [eventToolbar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(eventInputView);
        make.height.mas_equalTo(44);
    }];
    
    [self.eventPicker mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(eventToolbar.mas_bottom);
        make.left.right.bottom.equalTo(eventInputView);
    }];
    
    self.monthField.inputView = monthInputView;
    self.eventField.inputView = eventInputView;
    // 约束
    CGFloat statusBarHeight = [UIApplication sharedApplication].statusBarFrame.size.height;
    CGFloat navBarHeight = 44.0;
    CGFloat topBarHeight = statusBarHeight + navBarHeight;
    [self.headerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.view);
        make.height.mas_equalTo(topBarHeight);
    }];
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.headerView.mas_top).offset(60);
        make.centerX.equalTo(self.headerView.mas_centerX).offset(0);
    }];
    
    [self.backButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.headerView).offset(16);
        make.top.equalTo(self.headerView.mas_top).offset(40);
        make.width.height.mas_equalTo(44);
    }];
    // 搜索容器视图约束
    [self.searchContainerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view).inset(16);
        make.top.equalTo(self.titleLabel.mas_bottom).offset(20);
        make.height.mas_equalTo(60);
    }];
    
    [self.monthField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.searchContainerView).offset(16);
        make.centerY.equalTo(self.searchContainerView);
        make.right.equalTo(self.separatorLine.mas_left).offset(-16);
        make.height.mas_equalTo(40);
    }];
    
    [self.separatorLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.searchContainerView);
        make.centerY.equalTo(self.searchContainerView);
        make.width.mas_equalTo(1);
        make.height.mas_equalTo(40);
    }];
    
    [self.eventField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.separatorLine.mas_right).offset(16);
        make.centerY.equalTo(self.searchContainerView);
        make.right.equalTo(self.searchButton.mas_left).offset(-16);
        make.height.mas_equalTo(40);
    }];
    
    [self.searchButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.searchContainerView).offset(-16);
        make.centerY.equalTo(self.searchContainerView);
        make.width.height.mas_equalTo(36);
    }];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.searchContainerView.mas_bottom).offset(20);
        make.left.right.bottom.equalTo(self.view).inset(12);
    }];
    
    [self.emptyView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.tableView);
    }];
    
    // 设置monthField的默认值为当前月份
    if (self.monthOptions.count > 0) {
        self.monthField.text = self.monthOptions[0];
    }
    
    // 设置eventField的默认值为第一个事件
    if (self.eventOptions.count > 0) {
        self.eventField.text = self.eventOptions[0];
    }
    
    // 初始化空数据提示视图的显示状态
    [self updateEmptyViewVisibility];
}
#pragma mark - Actions

- (void)backButtonTapped {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellId = @"GoodDayCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
        cell.selected = UITableViewCellSelectionStyleNone;
        cell.backgroundColor = [UIColor clearColor];
        UIView *bg = [[UIView alloc] init];
        bg.backgroundColor = [UIColor colorWithRed:0.996 green:0.969 blue:0.839 alpha:1.0];
        bg.layer.cornerRadius = 16;
        bg.layer.masksToBounds = YES;
        [cell.contentView addSubview:bg];
        [bg mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(cell.contentView).inset(8);
        }];
        UILabel *dateLabel = [[UILabel alloc] init];
        dateLabel.tag = 101;
        dateLabel.font = [UIFont boldSystemFontOfSize:18];
        dateLabel.textColor = [UIColor colorWithRed:0.773 green:0.188 blue:0.188 alpha:1.0];
        [bg addSubview:dateLabel];

        UILabel *lunarLabel = [[UILabel alloc] init];
        lunarLabel.tag = 102;
        lunarLabel.font = [UIFont systemFontOfSize:14];
        lunarLabel.textColor = [UIColor colorWithRed:0.6 green:0.6 blue:0.6 alpha:1.0];
        lunarLabel.textAlignment = NSTextAlignmentRight;
        [bg addSubview:lunarLabel];
        
        UILabel *yiLabel = [[UILabel alloc] init];
        yiLabel.tag = 103;
        yiLabel.font = [UIFont systemFontOfSize:15];
        yiLabel.textColor = [UIColor colorWithRed:0.4 green:0.3 blue:0.2 alpha:1.0];
        yiLabel.numberOfLines = 0; // 支持多行显示
        yiLabel.lineBreakMode = NSLineBreakByWordWrapping; // 按单词换行
        [bg addSubview:yiLabel];
        
        UILabel *jiLabel = [[UILabel alloc] init];
        jiLabel.tag = 104;
        jiLabel.font = [UIFont systemFontOfSize:15];
        jiLabel.textColor = [UIColor colorWithRed:0.6 green:0.6 blue:0.6 alpha:1.0];
        jiLabel.numberOfLines = 0; // 支持多行显示
        jiLabel.lineBreakMode = NSLineBreakByWordWrapping; // 按单词换行
        [bg addSubview:jiLabel];
        [dateLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.top.equalTo(bg).offset(16);
        }];
        [lunarLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(bg).offset(16);
            make.top.equalTo(dateLabel.mas_bottom).offset(12);
        }];
        [yiLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(bg).offset(16);
            make.right.equalTo(bg).offset(-12);
            make.top.equalTo(lunarLabel.mas_bottom).offset(12);
        }];
        
        [jiLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(bg).offset(16);
            make.right.equalTo(bg).offset(-12);
            make.top.equalTo(yiLabel.mas_bottom).offset(12);
            make.bottom.equalTo(bg).offset(-16);
        }];
    }
    NSDictionary *item = self.dataSource[indexPath.row];
    UILabel *dateLabel = [cell viewWithTag:101];
    UILabel *lunarLabel = [cell viewWithTag:102];
    UILabel *yiLabel = [cell viewWithTag:103];
    UILabel *jiLabel = [cell viewWithTag:104];
    dateLabel.text = item[@"date"];
    
    // 格式化农历信息
    NSString *lunarText = item[@"lunar"];
    if ([lunarText isKindOfClass:[NSString class]] && [lunarText length] > 0) {
        lunarLabel.text = [self formatLunarString:lunarText];
    } else {
        lunarLabel.text = @"";
    }
    
    // 处理宜事项显示
    id yiData = item[@"yi"];
    if ([yiData isKindOfClass:[NSString class]] && [(NSString *)yiData length] > 0) {
        NSString *yiText = [NSString stringWithFormat:@"宜：%@", yiData];
        yiLabel.attributedText = [self highlightEventInText:yiText withEvent:self.eventField.text];
    } else {
        yiLabel.text = @"宜：无";
    }
    
    // 处理忌事项显示
    id jiData = item[@"ji"];
    if ([jiData isKindOfClass:[NSString class]] && [(NSString *)jiData length] > 0) {
        jiLabel.text = [NSString stringWithFormat:@"忌：%@", jiData];
    } else {
        jiLabel.text = @"忌：无";
    }
    
    return cell;
}

#pragma mark - UIPickerViewDataSource & Delegate
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    if (pickerView == self.monthPicker) return self.monthOptions.count;
    return self.eventOptions.count;
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    if (pickerView == self.monthPicker) return self.monthOptions[row];
    return self.eventOptions[row];
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    if (pickerView == self.monthPicker) {
        self.monthField.text = self.monthOptions[row];
    } else {
        self.eventField.text = self.eventOptions[row];
    }
}

#pragma mark - 搜索事件
- (void)searchAction {
    // 点击搜索按钮时，从datalist中搜索数据
    [self searchDataFromDatalist];
}

#pragma mark - 月份选择器按钮事件
- (void)monthCancelTapped {
    [self.monthField resignFirstResponder];
}

- (void)monthDoneTapped {
    [self.monthField resignFirstResponder];
    // 可以在这里添加月份选择完成后的逻辑
}

#pragma mark - 事件选择器按钮事件
- (void)eventCancelTapped {
    [self.eventField resignFirstResponder];
}

- (void)eventDoneTapped {
    // 如果用户没有选择任何事件，默认选择第一个
    if (!self.eventField.text || [self.eventField.text length] == 0) {
        NSInteger selectedRow = [self.eventPicker selectedRowInComponent:0];
        if (selectedRow >= 0 && selectedRow < self.eventOptions.count) {
            self.eventField.text = self.eventOptions[selectedRow];
        } else if (self.eventOptions.count > 0) {
            self.eventField.text = self.eventOptions[0];
        }
    }
    
    [self.eventField resignFirstResponder];
    // 当事件选择完成时，从datalist中搜索数据
    [self searchDataFromDatalist];
}

#pragma mark - 生成月份选项
- (NSArray *)generateMonthOptions {
    NSMutableArray *monthOptions = [NSMutableArray array];
    NSDate *currentDate = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth fromDate:currentDate];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy年MM月";
    
    for (int i = 0; i < 12; i++) {
        NSDate *targetDate = [calendar dateByAddingUnit:NSCalendarUnitMonth value:i toDate:currentDate options:0];
        NSString *monthString = [formatter stringFromDate:targetDate];
        [monthOptions addObject:monthString];
    }
    
    return [monthOptions copy];
}

#pragma mark - 从datalist搜索数据
- (void)searchDataFromDatalist {
    if (!self.eventField.text || [self.eventField.text length] == 0) {
        NSLog(@"请先选择事件");
        return;
    }
    
    NSString *selectedEvent = self.eventField.text;
    NSMutableArray *searchResults = [NSMutableArray array];
    
    // 获取当前日期
    NSDate *currentDate = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    
    // 搜索未来12个月的数据
    for (int i = 0; i < 12; i++) {
        NSDate *targetDate = [calendar dateByAddingUnit:NSCalendarUnitMonth value:i toDate:currentDate options:0];
        NSDateComponents *components = [calendar components:NSCalendarUnitYear fromDate:targetDate];
        NSString *year = [NSString stringWithFormat:@"%ld", (long)components.year];
        
        NSLog(@"正在搜索 %@ 年的数据", year);
        
        // 构建JSON文件路径
        NSString *fileName = [NSString stringWithFormat:@"huangli_%@.json", year];
        NSString *filePath = [[NSBundle mainBundle] pathForResource:fileName ofType:nil inDirectory:@"dataList"];
        
        if (!filePath) {
            // 尝试直接查找文件
            filePath = [[NSBundle mainBundle] pathForResource:fileName ofType:nil];
        }
        
        if (!filePath) {
            NSLog(@"未找到数据文件: %@", fileName);
            continue;
        }
        
        // 读取JSON文件
        NSData *jsonData = [NSData dataWithContentsOfFile:filePath];
        if (!jsonData) {
            NSLog(@"无法读取数据文件: %@", filePath);
            continue;
        }
        
        // 解析JSON
        NSError *error;
        NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
        if (error) {
            NSLog(@"JSON解析错误: %@", error.localizedDescription);
            continue;
        }
        
        // 搜索包含选定事件的日期
        for (NSDictionary *dayData in jsonArray) {
            id jiData = dayData[@"yi"];
            if ([jiData isKindOfClass:[NSString class]] && [(NSString *)jiData containsString:selectedEvent]) {
                // 格式化日期显示
                NSString *dateString = dayData[@"date"];
                NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
                formatter.dateFormat = @"yyyy-MM-dd";
                NSDate *date = [formatter dateFromString:dateString];
                
                formatter.dateFormat = @"yyyy年MM月dd日";
                NSString *formattedDate = [formatter stringFromDate:date];
                
                // 获取星期
                NSCalendar *weekCalendar = [NSCalendar currentCalendar];
                NSDateComponents *weekComponents = [weekCalendar components:NSCalendarUnitWeekday fromDate:date];
                NSArray *weekdays = @[@"", @"周日", @"周一", @"周二", @"周三", @"周四", @"周五", @"周六"];
                NSString *weekday = weekdays[weekComponents.weekday];
                
                NSString *fullDateString = [NSString stringWithFormat:@"%@ %@", formattedDate, weekday];
                
                // 创建结果字典
                NSDictionary *result = @{
                    @"date": fullDateString,
                    @"lunar": [dayData[@"nongli"] isKindOfClass:[NSString class]] ? dayData[@"nongli"] : @"",
                    @"yi": [dayData[@"yi"] isKindOfClass:[NSString class]] ? dayData[@"yi"] : @"",
                    @"ji": [dayData[@"ji"] isKindOfClass:[NSString class]] ? dayData[@"ji"] : @""
                };
                
                [searchResults addObject:result];
            }
        }
    }
    
    // 更新数据源并刷新表格
    self.dataSource = [searchResults copy];
    [self.tableView reloadData];
    
    NSLog(@"搜索完成，找到 %lu 个结果", (unsigned long)searchResults.count);
    
    // 更新空数据提示视图的显示状态
    [self updateEmptyViewVisibility];
}

#pragma mark - 更新空数据提示视图显示状态
- (void)updateEmptyViewVisibility {
    if (self.dataSource.count == 0) {
        self.emptyView.hidden = NO;
        self.tableView.hidden = YES;
    } else {
        self.emptyView.hidden = YES;
        self.tableView.hidden = NO;
    }
}

#pragma mark - 检查可用数据文件
- (void)checkAvailableDataFiles {
    NSLog(@"检查可用的数据文件...");
    
    // 检查2025年的数据文件
    NSString *testFile = @"huangli_2025.json";
    NSString *filePath1 = [[NSBundle mainBundle] pathForResource:testFile ofType:nil inDirectory:@"dataList"];
    NSString *filePath2 = [[NSBundle mainBundle] pathForResource:testFile ofType:nil];
    
    NSLog(@"dataList目录下查找 %@: %@", testFile, filePath1 ? @"找到" : @"未找到");
    NSLog(@"根目录下查找 %@: %@", testFile, filePath2 ? @"找到" : @"未找到");
    
    // 列出Bundle中的所有文件
    NSArray *bundleFiles = [[NSBundle mainBundle] pathsForResourcesOfType:@"json" inDirectory:nil];
    NSLog(@"Bundle中的所有JSON文件数量: %lu", (unsigned long)bundleFiles.count);
    
    NSArray *dataListFiles = [[NSBundle mainBundle] pathsForResourcesOfType:@"json" inDirectory:@"dataList"];
    NSLog(@"dataList目录中的JSON文件数量: %lu", (unsigned long)dataListFiles.count);
}

#pragma mark - 格式化农历信息
- (NSString *)formatLunarString:(NSString *)lunarString {
    if (!lunarString || [lunarString length] == 0) {
        return lunarString;
    }
    
    NSMutableString *formattedString = [NSMutableString stringWithString:lunarString];
    
    // 在年月日后加空格
    NSRange yearRange = [formattedString rangeOfString:@"年"];
    if (yearRange.location != NSNotFound) {
        [formattedString insertString:@" " atIndex:yearRange.location + 1];
    }
    
    NSRange monthRange = [formattedString rangeOfString:@"月"];
    if (monthRange.location != NSNotFound) {
        [formattedString insertString:@" " atIndex:monthRange.location + 1];
    }
    
    NSRange dayRange = [formattedString rangeOfString:@"日"];
    if (dayRange.location != NSNotFound) {
        [formattedString insertString:@" " atIndex:dayRange.location + 1];
    }
    
    // 在第一个"周"前加空格
    NSRange firstWeekRange = [formattedString rangeOfString:@"周"];
    if (firstWeekRange.location != NSNotFound) {
        [formattedString insertString:@" " atIndex:firstWeekRange.location];
    }
    
    // 在"第"前加空格
    NSRange diRange = [formattedString rangeOfString:@"第"];
    if (diRange.location != NSNotFound) {
        [formattedString insertString:@" " atIndex:diRange.location];
    }
    
    return formattedString;
}

#pragma mark - 高亮显示事件
- (NSAttributedString *)highlightEventInText:(NSString *)text withEvent:(NSString *)event {
    if (!text || !event || [event length] == 0) {
        return [[NSAttributedString alloc] initWithString:text ?: @""];
    }
    
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:text];
    
    // 设置默认样式
    [attributedString addAttribute:NSFontAttributeName 
                            value:[UIFont systemFontOfSize:15] 
                            range:NSMakeRange(0, attributedString.length)];
    [attributedString addAttribute:NSForegroundColorAttributeName 
                            value:[UIColor colorWithRed:0.4 green:0.3 blue:0.2 alpha:1.0] 
                            range:NSMakeRange(0, attributedString.length)];
    
    // 查找并高亮事件
    NSRange searchRange = NSMakeRange(0, attributedString.length);
    NSRange foundRange;
    
    while ((foundRange = [text rangeOfString:event options:NSCaseInsensitiveSearch range:searchRange]).location != NSNotFound) {
        // 设置主题色
        [attributedString addAttribute:NSForegroundColorAttributeName 
                                value:[UIColor colorWithRed:0.773 green:0.188 blue:0.188 alpha:1.0] 
                                range:foundRange];
        
        // 更新搜索范围
        searchRange.location = foundRange.location + foundRange.length;
        searchRange.length = attributedString.length - searchRange.location;
    }
    
    return attributedString;
}

@end
